package com.qf.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.feign.OrderFeignClient;
import com.qf.pojo.Order;
import com.qf.pojo.Result;
import com.qf.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/user")
@DefaultProperties(defaultFallback = "defaultFallback")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private OrderFeignClient orderFeignClient;

    /*
        默认降级方法，要求空参，但是返回值必须和业务方法的返回值一样
     */
    public Result defaultFallback(){
        return Result.error("服务器忙，稍后重试~~default...");
    }


    @GetMapping("/{id}")
    //设置降级方法
   /* @HystrixCommand(commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),

            //在10s中内，访问最少4次，错误比例达到50%，就会触发熔断开关
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "4"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //滑动时间窗
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")

    },
        threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "15")
        }
    )*/
    @HystrixCommand
    public Result findById(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        user.setUsername("zhangsan" + id);
        //订单（通过订单服务，查询用户的订单）.基于rest风格发起远程调用
//        Result orderResult = restTemplate.getForObject("http://localhost:81/order/"+id, Result.class);

        //这里不要再写ip:端口了,直接写服务的名称,内部会通过服务名称到注册中心获取这个服务的ip 端口信息
//        Result orderResult = restTemplate.getForObject("http://ORDER-PROVIDER/order/"+id, Result.class);

        Result orderResult = orderFeignClient.findByUid(id);
        if (orderResult != null && orderResult.isFlag()){
            List<Order> orders = (List<Order>) orderResult.getData();
            user.setOrders(orders);
        }else{
            return orderResult;
        }

        return Result.success("查询成功",user);
    }

    /*
        降级方法必须和原来的目标方法同参同返回值
     */
    public Result fallback(Integer id){
        //返回降级后的假数据
        return Result.error("服务器忙，稍后重试~~");
    }


}
